import sys
import os
import time
import math
BASE_PATH = os.path.dirname(
    os.path.dirname(os.path.abspath(__file__))
)
sys.path.insert(0,BASE_PATH)

from bin import get_Webdriver



class History_Work:
    def __init__(self):
        self.driver = get_Webdriver.Get_Webdriver().driver


    # def in_onlineEditByHistoryWork(self,workId):
    #     """通过点击历史任务进入在线编辑界面"""
    #     self.findHistoryWork(workId)
    #     findFlag = True
    #     historyWorkNumber = len(self.getHistoryWorkList())
    #     for i in range(1, historyWorkNumber):
    #         if self.dr.find_element_by_xpath(".//*[@id='history']/tbody/tr[" + str(i) + "]/td[1]").text == workId:
    #             self.dr.find_element_by_xpath(".//*[@id='history']/tbody/tr[" + str(i) + "]/td[8]/a[2]").click()
    # def stopWork(self):
    #     """停止全部任务"""
    #     self.dr.find_element_by_xpath(ReadConfig().stopWork_button_xpath).click()
    #     self.clickOKButton()
    #     time.sleep(0.3)
    #     self.clickOKButton()
    #
    # def getUserCount(self):
    #     """获取当前条件下用户个数"""
    #     time.sleep(2)
    #     try:
    #         return int(((self.dr.find_element_by_xpath(self.r.userCount_text_xpath).text).split(" "))[5])
    #     except IndexError:
    #         if "没有找到匹配的记录" in self.dr.find_element_by_xpath(self.r.userEmptyList_text_xpath).text:
    #             return "用户列表为空"
    def findHistoryWork(self, id=None, state=None, searchword=None):
        """检索历史任务  state -1-->完成 1-->进行中 2-->失败"""
        if id:
            self.driver.type("id=>search_id", id)
        if state:
            self.driver.select_value("id=>search_status", state)
        if searchword:
            self.driver.type("id=>search_word", searchword)
        time.sleep(0.5)
        self.driver.click("id=>search_history")

    def getHistoryWorkListDetails(self, workId):
        """获取历史任务的详情,目前仅支持按照任务ID精确检索"""
        self.findHistoryWork(workId)
        findFlag = True
        getHistoryCount = self.getHistoryCount()
        for i in range(1, getHistoryCount+1):
            if self.dr.find_element_by_xpath(".//*[@id='history']/tbody/tr[" + str(i) + "]/td[1]").text == workId:
                self.dr.find_element_by_xpath(".//*[@id='history']/tbody/tr[" + str(i) + "]/td[2]/a").click()
                # self.dr.find_element_by_xpath(".//*[@id='history']/tbody/tr[" + str(i) + "]/td[2]/a").click()
                findFlag = False
        if findFlag:
            raise UserWarning("未找到需要查看详情的任务")
        self.dr.switch_to_frame(self.dr.find_element_by_xpath(ReadConfig().historyWorkDetails_frame_xpath))
        historyWorkListDetails = self.dr.find_element_by_xpath(ReadConfig().historyWorkDetails_text_xpath).text
        # self.dr.find_element_by_xpath(".//*[@i='close']").click()
        # self.dr.switch_to_default_content()
        self.dr.refresh()
        time.sleep(1)
        return historyWorkListDetails

    def getallHistoryCount(self):
        """获取当前条件下所有历史任务个数"""
        time.sleep(1)
        try:
            return int(self.driver.get_text('css=>.pagination-info').split(" ")[5])
        except IndexError:
            return "文件列表为空"

    def getHistoryCount(self):
        """获取当前页面历史任务个数"""
        time.sleep(1)
        try:
            lastcount = int(self.driver.get_text('css=>.pagination-info').split(" ")[3])
        except IndexError:
            return "文件列表为空"
        else:
            firstcount = int(self.driver.get_text('css=>.pagination-info').split(" ")[1])
            count = lastcount - firstcount
            return count


    def getCurrentHisoryList(self):
        """返回用户列表详情 list格式 标题\n分割  用户信息空格分割 最多返回10条"""
        historyNumber = self.getHistoryCount()
        # print(historyNumber)
        if historyNumber == "历史任务列表为空":
            return "历史任务列表为空"
        historyLists = []
        tElements = self.dr.find_elements_by_xpath(".//*[@id='history']/tbody/tr")
        # print(len(tElements))
        for i in range(len(tElements)):
            historyList=[]
            details = self.dr.find_elements_by_xpath(".//*[@id='history']/tbody/tr[{}]/td".format(str(i+1)))
            for detail in details:
                historyList.append(detail.text)
            historyLists.append(historyList)
        return historyLists

    def getAllUserlist(self):
        """返回所有用户列表详情 list格式  用户信息空格分割 最多返回100条"""
        userList = []
        time.sleep(2)
        historyNumber = self.getHistoryCount()
        if historyNumber == "历史任务列表为空":
            return "历史任务列表为空"
        totalPageNumber = math.ceil(historyNumber / 10)
        currentPageNumber = 1
        overFlag = False
        for i in range(10):
            if overFlag: break
            for i in range(10):
                try:
                    userList.append(
                        self.dr.find_element_by_xpath(".//*[@id='maingrid']/tbody/tr[" + str(i + 1) + "]").text)
                except:
                    overFlag = True
                    break
            if overFlag: break
            if currentPageNumber >= totalPageNumber: break
            try:
                currentPageNumber = currentPageNumber + 1
                self.dr.find_element_by_xpath(self.r.nextPage_button_xpath).click()
            except:
                overFlag = True
        return userList

if __name__ == '__main__':
    Login_Action().login("18888888889","000000")
    Menu().in_HistoryWork()
    historyList=HistoryWork().getCurrentHisoryList()
    print(historyList)
    historyDetail = HistoryWork().getHistoryWorkListDetails("515207070255104")
    print(historyDetail)
